﻿using System;
using System.Collections.Generic;
using System.Text;

namespace 观察者模式
{
    public class WeatcherData : ISubject
    {
        public double Temperature { get; set; }
        public double Humidity { get; set; }
        public IList<IObserver> Observers { get; set; }

        public void GetData()
        {
            var rand = new Random();
            Temperature = rand.Next(-40, 40) + rand.NextDouble();
            Humidity = rand.Next(0, 100) + rand.NextDouble();
            HasChange = true;
            NotifyObserver(new { Temperature, Humidity });
        }

        public bool HasChange { get; set; }
        public WeatcherData()
        {
            Observers = new List<IObserver>();
        }
        public void AddObserver(IObserver observer)
        {
            if (!Observers.Contains(observer))
            {
                Observers.Add(observer);
            }
        }

        public void NotifyObserver(object arg)
        {
            if (HasChange)
            {
                foreach (var item in Observers)
                {
                    item.Update(this, arg);
                }
            }
            HasChange = false;
        }

        public void NotifyObserver()
        {
            NotifyObserver(null);
        }

        public void RemoveObserver(IObserver observer)
        {
            if (Observers.Contains(observer))
            {
                Observers.Remove(observer);
            }
        }
    }
}
